using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Reflection;
using ZoneFiveSoftware.Common.Data.Fitness;

namespace FilteredStatistics.Common.Controller
{
    class ProxyFilterCriteriaProvider : IFilterCriteriaProvider
    {
        public ProxyFilterCriteriaProvider(object provider)
        {
            if (provider == null)
            {
                throw new Exception("Invalid provider pointer");
            }

            Type providerType = provider.GetType();

            m_ProviderObject = provider;

            m_FilterCriteriasMethod = providerType.GetMethod("GetFilterCriterias", new Type[] { typeof(ILogbook) });
            m_FilterCriteriasChangedEvent = providerType.GetEvent("FilterCriteriasChanged");

            if (m_FilterCriteriasMethod == null ||
                m_FilterCriteriasMethod.ReturnType != typeof(IList<object>) ||
                m_FilterCriteriasChangedEvent == null)
            {
                throw new Exception("Provider doesn't implement IFilterCriteriaProvider interface");
            }

            m_FilterCriteriasChangedEvent.AddEventHandler(m_ProviderObject, Delegate.CreateDelegate(typeof(PropertyChangedEventHandler), this, "FilterCriteriasChangedEventHandler"));
        }

#region IFilterCriteriaProvider Members

        public IList<object> GetFilterCriterias(ILogbook logbook)
        {
            return m_FilterCriteriasMethod.Invoke(m_ProviderObject, new object[] { logbook }) as IList<object>;
        }

        public event PropertyChangedEventHandler FilterCriteriasChanged;

#endregion

        private void FilterCriteriasChangedEventHandler(object sender, PropertyChangedEventArgs e)
        {
            if (FilterCriteriasChanged != null)
            {
                FilterCriteriasChanged(this, e);
            }
        }

        private object m_ProviderObject = null;
        private MethodInfo m_FilterCriteriasMethod = null;
        private EventInfo m_FilterCriteriasChangedEvent = null;
    }
}
